package com.jzsm.modules.sender.senderService.impl.weixin;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.jzsm.modules.sender.bo.message.MessageBo;
import com.jzsm.modules.sender.enums.ChannelTypeEnum;
import com.jzsm.common.annotation.Channel;
import com.jzsm.common.utils.AssertUtils;
import com.jzsm.modules.sender.pojo.PushChannelAccount;
import com.jzsm.modules.sender.bo.accountConfig.RobotConfigBo;
import com.jzsm.modules.sender.senderService.AbstractMessageSender;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import org.springframework.stereotype.Component;

import java.net.HttpURLConnection;
import java.util.Map;
import java.util.Objects;

/**
 * 企业微信机器人 渠道
 */
@Channel(ChannelTypeEnum.WorkWeixinRobot)
@Component
@FieldDefaults(level = AccessLevel.PRIVATE)
public class WorkWeixinRobotMessageSender extends AbstractMessageSender {

    @Override
    public String sendMessage(String message, PushChannelAccount account) {
        return run(message, account);
    }

    @Override
    public String sendMessage(MessageBo messageBo) {
        return run(messageBo.getMessage(), messageBo.getAccount());
    }

    private String run(String message, PushChannelAccount account) {
        RobotConfigBo configBo = JSON.parseObject(account.getAccountConfig(), RobotConfigBo.class);
        final String url = configBo.getWebhook();
        AssertUtils.isNotBlank("Webhook 参数允许为空！该参数为机器人URL;", url);
        HttpResponse httpResponse = HttpRequest.post(url).body(message).execute();
        if (httpResponse.getStatus() != HttpURLConnection.HTTP_OK) {
            // todo 发送失败处理
            AssertUtils.throwError(httpResponse.body());
        }
        Map map = JSON.parseObject(httpResponse.body(), Map.class);

        AssertUtils.isTrue(httpResponse.body(), Objects.equals(map.get("errcode"), 0));
        return httpResponse.body();
    }

}
